#define _XOPEN_SOURCE  1
#define _BSD_SOURCE 1
#define _XOPEN_SOURCE_EXTENDED 1
#define _SVID_SOURCE  1
#define _POSIX_SOURCE  1
#include <header.h>
#include <shadow.h>
#include <errno.h>
#include <openssl/md5.h>

/**
 * @brief 获得空洞文件的已写入偏移量
*/
off_t getActualWrittenSize(const char *path) {
    int fd = open(path, O_RDONLY);

    struct stat st;
    fstat(fd, &st);

    unsigned char *file_data = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);

    off_t actual_size = 0;
    for (off_t i = 0; i < st.st_size; ++i) {
        if (file_data[i] != 0) {
            actual_size = i + 1;
        }
    }

    munmap(file_data, st.st_size);
    close(fd);
    return actual_size;
}



int main(int argc, char *argv[]) {
    const char *file = "1.txt";
    int fd = open(file, O_CREAT | O_TRUNC | O_RDWR, 0664);
    // 1 byte = 8 bit 
    ftruncate(fd, 1024);
    write(fd, "helloworld!", 11);
    close(fd);


    int fd2 = open(file, O_RDWR);  
    long offset = getActualWrittenSize(file);
    lseek(fd2,offset, SEEK_SET);
    void *p = mmap(NULL, 1024, PROT_READ | PROT_WRITE, MAP_SHARED, fd2, offset);
    write(fd, "i am a stu", 10);

    munmap(p, 1024);
    close(fd2);
    return 0;
}
